import 'package:todo_app/controllers/definitions/UserModel.dart';
import 'package:todo_app/utils/db/DBDataType.dart';
import 'package:todo_app/utils/db/DBHelper.dart';
import 'package:todo_app/utils/db/DBScheme.dart';

class UserDBUtils {
  static UserTable table = UserTable();

  static init() async {
    await table.init();
  }

  // 保存消息到本地
  static saveUser(UserModel user) async {
    if(user.id == null) return;
    var localMsg = await UserDBUtils.queryUserById(user.id!);
    if(localMsg != null) {
      // 更新本地消息
      await table.update(user);
    } else {
      // 插入本地消息
      await table.insert(user);
    }
  }

  // 查询本地消息
  static Future<UserModel?> queryUserById(int userId) async {
    return await table.findOneById(userId);
  }
}

class UserTable {
  DBHelper db = DBHelper(
    schemes: [
      DBScheme(columnName: "id", columnType: DBDataType.INTEGER, isPrimaryKey: true),
      DBScheme(columnName: "username", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "nickname", columnType: DBDataType.TEXT, isNull: true, sinceFrom: 2),
      DBScheme(columnName: "realname", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "email", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "mobile", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "default_group_id", columnType: DBDataType.INTEGER, isNull: true),
      DBScheme(columnName: "password", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "created_dt", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "last_login_time", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "avatar", columnType: DBDataType.TEXT, isNull: true),
      DBScheme(columnName: "pingPong", columnType: DBDataType.MAP, isNull: true, sinceFrom: 3),
    ],
    tableName: "t_user_v1",
    dbPath: "t_user_v1_20230626.db",
    version: 3
  );

  Future init() async {
    await db.open();
  }

  Future dispose() async {
    await db.close();
  }

  Future<int> insert(UserModel user) async {
    return await db.insert(user.toJson());
  }

  Future<int> update(UserModel user) async {
    return await db.update(user.toJson(), "id = ?", [user.id]);
  }

  Future<UserModel?> findOneById(int userId) async {
    UserModel user = UserModel();
    Map<String,dynamic>? map = (await db.where("id = ?", [userId]))?.first;
    if(map == null) return null;
    user.fromJson(map);
    return user;
  }
}
